/**
 Ceated by Amit Mudgal (MicroStrategy Principal Designer) for GMS on 6/20/2014
 *
 */
$(document).ready(function() {
	//$("input.phone").mask("(999) 999-9999");
	//$("input.prephone").mask("9999999999");
	jQuery.validator.addMethod("isName", function(value, element) {
		var name = /^[a-zA-Z]+$/;
		return this.optional(element) || (name.test(value));
		}, "Please remove any space, special mark, no ditigal");
	
	//remove the spave - string trim
	jQuery.validator.addMethod("regString", function(value, element) {
		return this.optional(element) || (value.indexOf("-") == -1) || (value.indexOf("(") == -1) || (value.indexOf(")") == -1);
		}, "Please remove '-', '(', ')', or space ");
	
	jQuery.validator.addMethod("noSingleQuote", function(value, element) {
		return this.optional(element) || (value.indexOf("'") == -1);
		}, "Please remove single quotes");
	
    jQuery.validator.addMethod("SelectSelected", function(value, element){
    	//alert(element);
    	return ($(element).val()!= -1);
    }, "Please select one value");
    
    jQuery.validator.addMethod("multiSelect", function(value, element){
    	return ($(element).val()!= null);
    }, "Please select one or more value");
    
    uam && uam.par && uam.par.validateSecFuncGroupRoleReason &&
    jQuery.validator.addMethod("parSecFuncGroupRole_Reason", uam.par.validateSecFuncGroupRoleReason, "Please select one or more value");
    
    jQuery.validator.addMethod("editSecFuncGroupRole_Reason", function(value, element){
    	if ($("#reasonOther").is(":checked") == true) {
    		return true;
    	} else {
    		for (var n in uam.eup.reasonList) {
    			if(uam.eup.reasonList[n] == true) {
    				return true;
    			}
    		}
    	}
    	return false;
    }, "Please select one or more value");
    
	$.mockjax({
		url: "emails.action",
		response: function(settings) {
			var email = settings.data.email,
				emails = ["glen@marketo.com", "george@bush.gov", "me@god.com", "aboutface@cooper.com", "steam@valve.com", "bill@gates.com"];
			this.responseText = "true";
			if ( $.inArray( email, emails ) !== -1 ) {
				this.responseText = "That's already taken.";
			}
		},
		responseTime: 500
	});
	
	/*=================== validate for PreApprovedRegistration page =================*/
	/*=================== validate for PreApprovedRegistration page =================*/
	/*=================== validate for PreApprovedRegistration page =================*/
	var validator = $("#preApprovedRegForm").validate({
		rules: {
			preVPName: "required",
			prelastname :{
				required: true,
				isName: true,
				minlength:2
			},
			prephone:{
				required: true,
				number: true,
				minlength: 10,
				maxlength: 10
				
			},
			preemail: {
				required: true,
				noSingleQuote: true,
				email: true
			},
			prefirstname:{
				required: true,
				minlength: 2,
				maxlength: 40
			},
			preMEmail: {
				required: true,
				noSingleQuote: true,
				email: true,
				remote: "emails.action"
			},
			preCostCenter: {
				required: true,
				maxlength: 18
			},
			predepartmentId: {
				required: true,
				maxlength: 7
			},
			funcGroupStep1 :{
				SelectSelected: true
			},
			destList: {
				multiSelect: true
			},
			premIn: {
				maxlength: 1
			},
			eupDeptDescDynamic: {
				required : true
			},
			reasonOtherContent: {
				parSecFuncGroupRole_Reason : true
			}
		},
		messages: {
			preVPName: "Enter a VP Name",
			prelastname:{
				required: "Enter your lastname",
				isName: "Please remove any special character and space, numeric value not allowed in name fields.",
				minlength: "Last Name no less than two chars"
			},
			prephone:{
				required: "Enter your phone number",
				number: "Enter your valid phone number with only digital",
				minlength: "Enter your valid phone number",
				maxlength :"Max is 10 digital numbers"
				
			}, 
			preemail: {
				required: "Enter an email address",
				noSingleQuote: "Please remove single quotes",
				email: "Enter a valid email address"
			},
			prefirstname:{
				 required: "Enter your firstname",
				 minlength: "First Name no less than two chars",
				 maxlength: "FIrst Name no more than 40 chars"
			},
			preMEmail: {
				required: "Please enter an email address",
				noSingleQuote: "Please remove single qutoes",
				email: "Please enter a valid email address",
				remote: jQuery.format("{0} is already in use")
			},
			preCostCenter: {
				required: "Cost Center is required",
				maxlength: "Cost Center no more than 18 chars"
			},
			predepartmentId:{
				required: "Enter department id",
				maxlength: "Department id length no more than 7"
			},
			premIn: {
				maxlength: "Enter no more than two chars"
			}
		},
		// specifying a submitHandler prevents the default submit, good for the demo
		submitHandler: function(form) {
			var options = form.destList.options;
			for(var i = 0; i<options.length; i++){
				var opt = options[i];
				opt.selected = true;
			}
			alert("form1");
			var taskUrl = "./taskProc?taskId=N001&taskEnv=xhr&taskContentType=json&TaskSubID=FormDataSubmit&rand=" + (new Date()).getTime();
			$(form).ajaxSubmit({
				type : "post",
				url : taskUrl,
				dataType : 'json',
				success : function(data) {
					console.log("data: " + data);
					if (data["status"] == 200) {
						//location.href = "../plugins/UAM/jsp/Exception-Access_Confirmation.jsp";
						alert("success");
					};					
				},
				error : function (XMLHttpRequest, textStatus, errorThrown) {
					console.log("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
				}
				
		    });
			return false;
	        
		},
		errorPlacement: function(error, element) {
			//alert("errorpreApprovedRegForm");
			if(element.attr("id") == "reasonOtherContent") {
				error.appendTo( element.next());
			} 
			else if ( element.is(":radio") )
				error.appendTo( element.parent().next().next() );
			else if ( element.is(":checkbox") )
				error.appendTo ( element.next() );
			else if ( element.attr("id") == "eupDeptDescDynamic" ) {
				error.appendTo( element.next() );
			} else {
				error.appendTo( element.parent().next() );
			}
		},
		
		success: function(label) {
			label.html("&nbsp;").addClass("checked");
		},
		highlight: function(element, errorClass) {
			$(element).parent().next().find("." + errorClass).removeClass("checked");
		}
	});
	
	/*************************************************************/
	var editUrProfForm = $("#editUrProfForm").validate({
		rules: {
			eupPhone:{
				required: true,
				number: true,
				minlength: 10,
				maxlength: 10
			},
			eupCC:{
				required: true,
				maxlength: 18
			},
			eupMFstName:{
				required: true,
				regString: true,
				minlength: 2,
				maxlength: 40
			},
		
			eupMgrLstName :{
				required: true,
				isName: true,
				minlength:2
			},
			eupMEmail: {
				required: true,
				noSingleQuote: true,
				email: true,
				remote: "emails.action"
			},
			eupMidName:{
				maxlength: 1,
				minlength: 0
			},
			eupEmail:{
				required: true,
				noSingleQuote: true,
				email: true,
				remote: "emails.action"
			},
			eupDeptDescDynamic: {
				"required" : true
			},
			destList:{
				"required" : true
			},
			reasonOtherContent: {
				"editSecFuncGroupRole_Reason" : true
			}
		},
		messages: {
			eupPhone:{
				required: "Enter your phone number",
				number: "Enter your valid phone number with only digital",
				minlength: "Enter your valid phone number",
				maxlength :"Max is 10 digital numbers"
			},
			eupCC:{
				required: "Enter cost center",
				maxlenght: "the max length is 18"
			},
			eupMFstName:{
				 required: "Enter your firstname",
				 regString: "Please remove '-', '(', ')', or space",
				 minlength: "First Name no less than two chars",
				 maxlength: "FIrst Name no more than 40 chars"
			},
		
			eupMgrLstName:{
				required: "Enter your last name",
				isName: "Please remove any special character and space, numeric value not allowed in name fields.",
				minlength: "Last Name no less than two chars"
			},
			eupMEmail: {
				required: "Please enter an email address",
				noSingleQuote: "Please remove single qutoes",
				email: "Please enter a valid email address",
				remote: jQuery.format("{0} is already in use")
			},
			eupMidName: {
				maxlength: "no more than two chars"
			},
			eupEmail: {
				required: "Please enter an email address",
				noSingleQuote: "Please remove single qutoes",
				email: "Please enter a valid email address",
				remote: jQuery.format("{0} is already in use")
			}
		},
		// specifying a submitHandler prevents the default submit, good for the demo
		submitHandler: function(form) {
			
			var options = form.destList.options;
			for(var i = 0; i<options.length; i++){
				var opt = options[i];
				opt.selected = true;
			}
			
			var checkedReasons = "";
			for (var reasonId in uam.eup.reasonList) {
				if (uam.eup.reasonList[reasonId]) {
					checkedReasons += reasonId + ",";
				}
			} 
			$("#reason").val(checkedReasons);
			
			var taskUrl = "./taskProc?taskId=N001&taskEnv=xhr&taskContentType=json&TaskSubID=EditUserProfile&rand=" + (new Date()).getTime();
			
			$(form).ajaxSubmit({
				type : "post",
				url : taskUrl,
				dataType : 'json',
				success : function(data) {
					
					console.log("response data: " + data);
					
					if (data["status"] == 200) {
						//location.href = "../plugins/UAM/jsp/Exception-Access_Confirmation.jsp";
						alert("success");
					} else {
						alert("error");
					};		
				},
				error : function (XMLHttpRequest, textStatus, errorThrown) {
					console.log("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
				}
				
		    });
			return false;
		},
		errorPlacement: function(error, element) {
			//alert("errorpreApprovedRegForm");
			if(element.attr("id") == "reasonOtherContent") {
				error.appendTo( element.next());
			} else if ( element.is(":radio") )
				error.appendTo( element.parent().next().next() );
			else if ( element.is(":checkbox") )
				error.appendTo ( element.next() );
			else
				error.appendTo( element.parent().next() );
		},
		
		success: function(label) {
			label.html("&nbsp;").addClass("checked");
		},
		highlight: function(element, errorClass) {
			$(element).parent().next().find("." + errorClass).removeClass("checked");
		}
	});

});